$(function () {
    // 滚动固定选项卡
    //eFixedFn('.learningCenter-history-list');
    //左右滚动方法
    new Swiper(".swiper-container-tuanCourse", {
        autoplay: 0,
        loop: 0,
        centeredSlides: 0,
        slidesPerView: "auto"
    });

    isApp();
    //获取学习统计数据
    userStudyBaseStatistics();

    //执行学习趋势图表
    getStudyLineFn();

    //获取所学课程数据
    loadMyCourseData(1);

    Zepto("body").on('click', '#buttons-tab>a', function () {
        var _this = Zepto(this);
        if (_this.hasClass('active')) return;
        var _id = this.id;
        changeTabs(_id);
    }).on("click",'#studyBtn',function () {
        loadMyCourseData(1)
    })


    function changeTabs(obj) {

        switch (obj) {
            case 'broadcastAll'://全部
                loadMyCourseData(1);
                break;
            case 'broadcastCourse'://点播
                loadMyCourseData(1);
                break;
            case'broadcastLive'://直播
                loadMyCourseData(1);
                break;
            case'broadcastPackage'://套餐
                loadMyCourseData(1);
                break;
            default:
                //专栏
                loadMyCourseData(1);
                break;
        }
    }

    // 课程加载
    function loadMyCourseData(pageNo) {
        var params = {
            "courseTypeKey": $("#courseTypeKey").val(),
            "expire": $("#studyBtn").attr("checked")
        };
        params = JSON.stringify(params);
        loadMobilePathData({
            url: baseloaction + '/mobile/uc/ajaxCourseList',
            contextId: 'course-list',
            pageNo: pageNo,
            pageCall: loadMyCourseData,
            params: params,
            callback: function (pageNo) {
            }
        });
    }
});


/**
 * 基本学习统计
 */
function userStudyBaseStatistics() {
    setTimeout(function () {
        $.ajax({
            url: baseloaction + '/mobile/uc/userStudyBaseStatistics',
            type: 'post',
            dataType: 'json',
            success: function (result) {
                var entity = result.entity;
                var userObj = entity.user;
                //累计观看(分钟)
                var studyTotalTime = userObj.studyTotalTime;
                if (studyTotalTime == null) {
                    studyTotalTime = 0;
                }
                if (studyTotalTime > 0) {
                    studyTotalTime = parseFloat(studyTotalTime / 60).toFixed(2);
                }
                setText('studyTotalTime', studyTotalTime, "");
                //今日学习时长
                var todayCount = userObj.todayCount;
                if (todayCount == null) {
                    todayCount = 0;
                }
                if (todayCount > 0) {
                    todayCount = parseFloat(todayCount / 60).toFixed(2);
                }
                setText('todayCount', todayCount, "");

                //完成课节数量
                var finishCount = userObj.finishCount;
                if (finishCount == null) {
                    finishCount = 0;
                }
                setText('finishCount', finishCount, "");
                //连续学习天数
                var continuityCount = userObj.continuityCount;
                if (continuityCount == null) {
                    continuityCount = 0;
                }
                setText('continuityCount', continuityCount, "");


                //参加直播场次(次)
                var joinLiveCount = userObj.joinLiveCount;
                if (joinLiveCount == null) {
                    joinLiveCount = 0;
                }
                setText('joinLiveCount', joinLiveCount, '参加直播场次:' + joinLiveCount + '次');

                //试卷(套)
                var examNum = userObj.examNum;
                if (examNum == null) {
                    examNum = 0;
                }
                setText('examNum', examNum, '试卷:' + examNum + '套');
                //总签到数(天)
                var signNum = userObj.signNum;
                if (signNum == null) {
                    signNum = 0;
                }
                setText('signNum', signNum, '总签到数:' + signNum + '天');
                var totalCount = parseInt(entity.examUserExpand.totalCount);
                var errorCount = parseInt(entity.examUserExpand.errorCount);
                if (entity.examUserExpand.totalCount == null || totalCount == 0) {
                    averagePrecision = 0;
                } else {
                    var _averagePrecision = parseFloat(totalCount - errorCount) / totalCount;
                    var averagePrecision = parseFloat(_averagePrecision * 100).toFixed(1);
                }
                setText('averagePrecision', averagePrecision, '正确率:' + averagePrecision + '%');


                setText('userName', entity.user.nickname, '');
                if (entity.user.avatar) {
                    $("#avatar").attr("src", entity.user.avatar)
                }
                if (entity.user.ranking == 2) {
                    $("#ranking").removeClass("leaRanking-one").addClass("leaRanking-two");
                } else if (entity.user.ranking == 3) {
                    $("#ranking").removeClass("leaRanking-one").addClass("leaRanking-three");
                } else if (entity.user.ranking==1) {
                    $("#ranking").removeClass("leaRanking-one").addClass("leaRanking-one");
                }else{
                    $("#ranking").removeClass("leaRanking-one").addClass("leaRanking-num");
                }


            }
        });
    });
}

/**
 * 设置内容显示
 * @param id 标签ID
 * @param num 数量
 * @param text title显示内容
 */
function setText(id, num, text) {
    $("#" + id).text(num);
}

function timeConversion(time) {
    var m = 0;
    var h = 0;
    if (time > 0) {
        time = parseInt(time / 60);
        m = parseInt(time % 60);
        h = (time - m) / 60;
    }
    return h + '时' + m + '分';
}


function enterCourse(courseType, courseId, courseImage, courseName) {
    var noMobile = getCookie("noMobile");
    if (noMobile != null) {
        if (noMobile == "1" ) {
            android.enterCourse(courseType, courseId, courseImage, courseName);
        }
        if (noMobile == '2') {
            var _cObj = {
                'courseType': courseType,
                'courseId': courseId,
                'courseImage': courseImage,
                'courseName': courseName
            }
            window.webkit.messageHandlers.enterCourse.postMessage(JSON.stringify(_cObj));
        }
        return true;
    }
    if (courseType == 'LIVE') {
        window.location.href = baseloaction + '/mobile/course/liveInfo?courseId=' + courseId;
    } else if(courseType == 'SMALL'){
        window.location.href = baseloaction + '/mobile/course/smallClassInfo?courseId=' + courseId;

    }else{
        window.location.href = baseloaction + '/mobile/course/info?onLimit=true&courseId=' + courseId;
    }
}

function goBack() {
    var noMobile = getCookie("noMobile");
    if (noMobile != null) {
        if (noMobile == "1") {
            android.goBack();
        }

        if (noMobile=='2') {
            setTimeout(function () {
                goBackIos();
            }, 0)
        }
        return true;
    }
    window.location.href = baseloaction + '/mobile/uc/index';
}
function goBackIos() {
    window.webkit.messageHandlers.goBack.postMessage("");
}

function getStudyLineFn() {
    var week = getWeekDay(new Date());
    $("#startTime").text(dateFormat("mm月dd日", week[0]));
    $("#endTime").text(dateFormat("mm月dd日", week[6]));
    var parameter = {'type': 1, 'endTime': week[6], 'startTime': week[0]};
    learningTrend(parameter, studyLineFn);
}

function studyLineFn(data) {

    var learTime = new Array();
    for (var i = 0; i < data.length; i++) {
        learTime.push(data[i].learntime);
    }
    var studyConfig = {
        type: 'line',
        data: {
            labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
            datasets: [{
                label: '学习时长(分钟)',
                backgroundColor: 'rgba(255, 178, 28,.5)',
                borderColor: 'rgb(255, 178, 28)',
                borderWidth: 1,
                data: learTime,
                fill: true
            }]
        },
        options: {
            legend: {
                position: 'bottom'
            },
            responsive: true,
            title: {
                display: false,
            },
            tooltips: {
                mode: 'index',
                intersect: false,
            },
            hover: {
                mode: 'nearest',
                intersect: true
            },
            scales: {
                xAxes: [{
                    display: true,
                    gridLines: {
                        'lineWidth': 0
                    },
                    scaleLabel: {
                        display: false
                    }
                }],
                yAxes: [{
                    display: true,
                    gridLines: {
                        color: "rgba(0, 0, 0, 0.03)"
                    },
                    scaleLabel: {
                        display: false
                    },
                    ticks: {
                        min: 0  //最小值
                    }
                }]
            }
        }
    };

    var ctx = document.getElementById('studyLineCanvas').getContext('2d');
    window.myLine = new Chart(ctx, studyConfig);
}
/**
 * 判断是否是app 嵌套
 */
function isApp() {
    var  noMobile  = getCookie("noMobile");
    if(noMobile!=null){
        if(noMobile=="1"){
            $(".menu").hide();
        }
    }
}